//
//  Stroke.m
//  Playground
//
//  Created by Basuke on 08/03/22.
//  Copyright 2008 Basuke's. All rights reserved.
//

#import "Stroke.h"


@implementation Stroke

@synthesize	penWidth;
@synthesize	alpha;
@synthesize	color;
@synthesize	bounds;

- (id)init {
	if (self = [super init]) {
		penWidth = 3.0;
		alpha = 0.5;
		color = [UIColor blackColor];
		bounds = CGRectZero;	
		_points = [[NSMutableArray arrayWithCapacity:100] retain];
	}
	
	return self;
}

- (void)dealloc {
	[_points release];
	
	[super dealloc];
}

- (id)reset {
	penWidth = 3.0;
	alpha = 0.5;
	color = [UIColor blackColor];
	bounds = CGRectZero;	
	[_points removeAllObjects];
	
	return self;
}

- (void)addPoint:(CGPoint)pt {
	NSValue *lastPoint = [_points lastObject];
	[_points addObject:[NSValue valueWithCGPoint:pt]];
	
	if (lastPoint) {
		CGRect pointBounds;
		pointBounds.origin = pt;
		pointBounds.size = CGSizeZero;
		pointBounds = CGRectInset(pointBounds, -penWidth, -penWidth);
		
		bounds = CGRectUnion(bounds, pointBounds);
	} else {
		bounds.origin = pt;
		bounds = CGRectInset(bounds, -penWidth, -penWidth);
	}
}

- (void)strokePath:(CGContextRef)context {
	CGContextBeginPath(context);
	
	CGContextSetLineWidth(context, self.penWidth);
	CGContextSetLineCap(context, kCGLineCapRound);
	CGContextSetStrokeColorWithColor(context, [color cgColor]);
	CGContextSetAlpha(context, alpha);
	
	BOOL firstPt = YES;
	for (NSValue *value in _points) {
		CGPoint pt = [value CGPointValue];
		
		if (firstPt) {
			CGContextMoveToPoint(context, pt.x, pt.y);
			firstPt = NO;
		} else {
			CGContextAddLineToPoint(context, pt.x, pt.y);
		}
	}
	CGContextStrokePath(context);
}


@end
